package com.itqf.typehandlers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * projectName: mybatis2103
 *
 * @author: 赵伟风
 * time: 2021/6/24 16:18
 * description:字符串转换成数组解析器
 */
@MappedTypes(Integer[].class) //java类型
@MappedJdbcTypes(JdbcType.VARCHAR)  //数据库类型
public class StringToIntegerArrayTypeHandler  extends BaseTypeHandler<Integer[]> {

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 设置属性
     *    Integer []  - string - preparedstatment
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {

        String arrayStr = null;
        try {
            arrayStr = objectMapper.writeValueAsString(parameter);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        ps.setObject(i,arrayStr);
    }


    /**
     * 获取属性
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {

        String ids = rs.getString(columnName); // '[1,2,3,4]'

        Integer[] idsArray = new Integer[0];
        try {
            idsArray = objectMapper.readValue(ids, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return idsArray;
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

        String ids = rs.getString(columnIndex);


        Integer[] idsArray = new Integer[0];
        try {
            idsArray = objectMapper.readValue(ids, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return idsArray;
    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

        String ids = cs.getString(columnIndex);


        Integer[] idsArray = new Integer[0];
        try {
            idsArray = objectMapper.readValue(ids, Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return idsArray;
    }
}
